#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>

void other_task()
{
    printf("The child process is still running, parent process is running other_task\n");
}

int main()
{
    pid_t id = fork();
    
    if(id == 0)
    {
       // printf("I am child procss, and my pid is %d\n",getpid());
        printf("I am child process, and I am running\n");
        sleep(5);
        exit(0);
    }


    //printf("sig:%d\ncore dump flag:%d\nending code:%d\n",status & 0x7f,(status>>7) & 1,(status>>8) & 0xff);
    
    //if(WIFEXITED(status))
    //{
    //    int ending_code = WEXITSTATUS(status);
    //    printf("%d\n",ending_code);
    //}

    //if(WIFSIGNALED(status))
    //{
    //    int sig = WTERMSIG(status);
    //    printf("%d\n",sig);
    //}
    
    int status = 0;
    while(1)
    {
        pid_t ret = waitpid(id,&status,WNOHANG);
        assert(ret>=0);

        if(ret > 0) // 子进程已退出
        {
            printf("ending code:%d\n",(status>>8) & 0xff);
            break;
        }

        else if(ret == 0) // 子进程尚未退出
        {
            other_task(); // 父进程执行其他任务
            sleep(1); // 休眠一秒后再进行下一次轮询
        }
    }
    return 0;
}
